package server

import (
	"common/database/config"
	"context"
	"errors"
	"user_srv/internal/models/dao"
	"user_srv/internal/models/service"
	pb "user_srv/proto"
)

type Server struct {
	pb.UnimplementedUserServer
}

func (c *Server) Register(ctx context.Context, request *pb.RegisterRequest) (*pb.RegisterResponse, error) {
	var you *dao.User
	config.DB.Where("name=?", request.Name).Find(&you).Limit(1)
	if you.ID != 0 {
		return nil, errors.New("医生注册失败,已经注册过了")
	}
	user := &dao.User{
		Name:      request.Name,
		Image:     request.Image,
		Where:     int(request.Where),
		ObjRoom:   int(request.ObjRoom),
		Job:       int(request.Job),
		Title:     int(request.Title),
		NumPrice:  float64(request.NumPrice),
		LookPrice: float64(request.LookPrice),
		Cont:      request.Cont,
	}
	err := config.DB.Create(&user).Error
	if err != nil {
		return nil, errors.New("医生注册失败")
	}
	Sync(user)
	return &pb.RegisterResponse{Id: int64(user.ID)}, nil
}

func (c *Server) Find(ctx context.Context, request *pb.FindRequest) (*pb.FindResponse, error) {
	sync := GetSync(request.KeyWord)
	if len(sync) == 0 {
		list := service.List()
		for _, user := range list {
			Sync(user)
		}
		syncAgain := GetSync(request.KeyWord)
		return &pb.FindResponse{Doctor: syncAgain}, nil
	}
	return &pb.FindResponse{Doctor: sync}, nil
}
